package com.jy.wms.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.joyi.gate.comm.SessionInfo;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.PropertyUtil;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.*;
import com.jy.wms.dao.WmsBoxMapper;
import com.jy.wms.dao.WmsReviewMapper;
import com.jy.wms.dao.WmsSetBoxMapper;
import com.jy.wms.pojo.SysHz;
import com.jy.wms.pojo.WmsBox;
import com.jy.wms.pojo.WmsReview;
import com.jy.wms.pojo.WmsSetBox;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName: WmsReviewService.java
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author Jane
 * @Date Tue Jan 30 10:19:46 CST 2018
 */

@Service
public class WmsReviewService extends BaseService<WmsReviewMapper,WmsReview> {

    @Autowired
    private WmsSetBoxMapper wmsSetBoxMapper;

    @Autowired
    private WmsBoxMapper wmsBoxMapper;

    @BaseServiceDescribe(moduleName = "出库复核",btnName = "出库复核异常处理扫码页面")
    public JSONObject getEdit(String xbh, HttpSession session)throws ServiceException{
        UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        Map<String,Object> map = wmsSetBoxMapper.getPrintByXbh(xbh,String.valueOf(userinfo.getUser().getOrgId().get(0)));
        //判断如果是 集拼箱编号则查询信息 如果不是则判断是否存在于集拼箱，如果是则获取集拼箱信息 如果不是则获取箱信息
        if(map != null){
            return getXmx(xbh,session);
        }else{
            String jpxId = dao.getBoxByXbh(xbh,String.valueOf(userinfo.getUser().getOrgId().get(0)));
            WmsReview wmsReview = dao.getByXbh(xbh,String.valueOf(userinfo.getUser().getOrgId().get(0)));
            if(wmsReview != null && wmsReview.getFhzt().equals("2")){
                if(!jpxId.equals("0")){
                    WmsSetBox wmsSetBox = wmsSetBoxMapper.baseSelectByPrimaryKey(jpxId);
                    xbh = wmsSetBox.getXbh();
                }
            }else{
                throw new ServiceException("该箱没有产生复核失败信息");
            }
            return getXmx(xbh,session);
        }
    }

    @BaseServiceDescribe(moduleName = "出库复核",btnName = "出库复核扫码页面")
    public JSONObject getXmx(String xbh, HttpSession session)throws ServiceException{
        UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        //判断该单是否已经复核过
        WmsReview wmsReview = dao.getByXbh(xbh,String.valueOf(userinfo.getUser().getOrgId().get(0)));
        if(wmsReview != null){
            if(wmsReview.getFhzt().equals("2")){
                throw new ServiceException("该单复核信息异常,请及时处理");
            }else{
                throw new ServiceException("此箱已复核完毕，不要重复操作");
            }
        } else{
            //获取装箱列表信息 如果装箱列表查询到改箱号则进行判断是否散箱
            List<Map<String,Object>> zxList = dao.getZxmx(xbh,String.valueOf(userinfo.getUser().getOrgId().get(0)));
            JSONObject json = new JSONObject();
            if(zxList.size()>0){
                if("0".equals(zxList.get(0).get("zslx").toString())){
                    throw new ServiceException("称重复核不包括整箱");
                }else{
                    Double zl = 0.0;
                    int i;
                    for( i = 0;i < zxList.size(); i++ ){
                        zl += Double.valueOf(zxList.get(i).get("zl").toString());
                    }
                    json.put("dydh",zxList.get(0).get("fydh").toString());
                    json.put("lxr",zxList.get(0).get("lxr").toString());
                    json.put("dz",zxList.get(0).get("dz").toString());
                    json.put("xx",zxList.get(0).get("xx").toString());
                    json.put("zl",zl);
                    json.put("zdzl",zl + Double.valueOf(zxList.get(0).get("zl").toString()));
                    json.put("zxzl",zl - Double.valueOf(zxList.get(0).get("zl").toString()));
                    json.put("contentList",zxList);
                    json.put("totals",zxList.size());
                    json.put("type",0);
                    json.putAll(wmsSetBoxMapper.getBoxNumber(xbh,String.valueOf(userinfo.getUser().getOrgId().get(0))));
                    return json;
                }
            }else{
                //集拼箱名称
                Map<String,Object> boxMap = wmsSetBoxMapper.getPrintByXbh(xbh,String.valueOf(userinfo.getUser().getOrgId().get(0)));
                if(boxMap != null && boxMap.size()>0){
                    json.putAll(boxMap);
                    json.put("fydh",wmsSetBoxMapper.getFydh(json.get("id").toString()));
                    WmsSetBox wmsSetBox = wmsSetBoxMapper.baseSelectByPrimaryKey(json.get("id").toString());
                    List<SysHz> hz=(List<SysHz>)session.getAttribute(BaseSessionInfo.SessionConsignor);
                    if(hz.size()>0){
                        json.put("hzmc",hz.get(0).getShow_hzid());
                    }
                    json.put("ckmc",userinfo.getUser().getOrgName());
                    json.put("cklxr",userinfo.getOrgs().get(0).getMaster());
                    json.put("lxr",wmsSetBox.getLxr());
                    json.put("dz",wmsSetBox.getDz());
                    String host = PropertyUtil.getProperty("safety.host");
                    String port = PropertyUtil.getProperty("safety.port");
                    String result = HttpUtil.doGet("http://"+host+":"+port+"/ms-safety/org/getOrgInfo/"+String.valueOf(userinfo.getUser().getOrgId().get(0)),session.getId());
                    json.put("ckdz", JSONObject.fromObject(result).get("address") == null?"":JSONObject.fromObject(result).get("address"));
                    json.put("kfrx",userinfo.getOrgs().get(0).getTelephone() == null?"":userinfo.getOrgs().get(0).getTelephone());
                    List<Map<String,Object>> list = wmsSetBoxMapper.getPrintList(json.get("id").toString());
                    json.put("list",list);
                    json.put("zdzl",Double.valueOf(json.get("zl").toString()) + Double.valueOf(list.get(0).get("zl").toString()));
                    json.put("zxzl",Double.valueOf(json.get("zl").toString()) - Double.valueOf(list.get(0).get("zl").toString()));
                    json.put("type",1);
                    return json;
                }else{
                    throw new ServiceException("查询失败");
                }

            }
        }
    }

    /**
     * 插入一条记录
     * @param entity 实体对象
     * @return int
     */
    public Integer baseInsert( WmsReview entity){
        return dao.baseInsert( entity );
    }

    /**
     * 插入一条记录（匹配有值的字段）
     * @param list 实体对象
     * @return int
     */
    @BaseServiceDescribe(moduleName = "出库复核",btnName = "新增出库复核")
    @Transactional
    public void baseInsertSelective( List<WmsReview> list,HttpSession session ) throws ServiceException,SucessException{
        //如果该箱已经在复核表内存在则全单不允许加入
        UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        Boolean type = true;
        StringBuffer msg = new StringBuffer();
        List<String> ids = new ArrayList<String>();
        for (WmsReview entity : list) {
            entity.setId(UUIDUtils.uuid());
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            entity.setFhsj(formatter.format(new Date()));
            entity.setCkid(String.valueOf(userinfo.getUser().getOrgId().get(0)));
            Integer count = dao.getCountByXbh(entity.getXbh(),String.valueOf(userinfo.getUser().getOrgId().get(0)));
            if(count > 0 ){
                type = false;
                msg.append(entity.getXbh());
                msg.append(",");
            }
            ids.add(entity.getId());
        }
        if(type){
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("fhzt",list.get(0).getFhzt().toString());
            map.put("list",ids);
            dao.updatePickingFhzt(map);
            dao.baseInsertAll(list);
            throw new SucessException("新增出库复核成功");
        }else{
            msg.append("箱编号已复核");
            throw new ServiceException(msg.toString());
        }
    }

    /**
     * 删除（根据主键ID删除）
     * @param id 主键
     * @return int
     */
    public Integer baseDeleteByPrimaryKey( String id){
        return dao.baseDeleteByPrimaryKey( id);
    }

    /**
     * 删除（根据ID 批量删除）
     * @param idList 主键ID列表
     * @return int
     */
    public Integer baseDeleteBathPrimaryKeys( List<String> idList){
        return dao.baseDeleteBathPrimaryKeys( idList );
    }

    /**
     * 分页查询
     * @param map 实际重量 width 箱编号 xbh
     * @return Page<WmsReview>
     */
    @BaseServiceDescribe(moduleName = "出库复核",btnName = "打印快递面单")
    public String print(Map<String,Object> map , HttpSession session) throws ServiceException {
        JSONObject json = new JSONObject();
        String message = "";
        try {
            String xbh = map.get("xbh").toString();
            //获取箱信息
            UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
            //判断该单是否已经复核过
            WmsReview wmsReview = dao.getByXbh(xbh,String.valueOf(userinfo.getUser().getOrgId().get(0)));
            if(wmsReview != null){
                if(wmsReview.getFhzt().equals("2")){
                    throw new ServiceException("该单复核信息异常,请及时处理");
                }else{
                    throw new ServiceException("此箱已复核完毕，不要重复操作");
                }
            } else{
                String lxr;
                String lxrdh;
                String sheng;
                String shi;
                String dz;
                Double zl = 0.0;
                Double sl = 0.0;
                List<Map<String,Object>> zxList = dao.getZxmx(xbh,String.valueOf(userinfo.getUser().getOrgId().get(0)));
                List<Map<String,Object>> jpxList = dao.getJpxMx(xbh,String.valueOf(userinfo.getUser().getOrgId().get(0)));
                if(zxList.size()>0){
                    lxr = zxList.get(0).get("lxr").toString();
                    lxrdh = zxList.get(0).get("lxrdh").toString();
                    sheng = zxList.get(0).get("sheng").toString();
                    shi = zxList.get(0).get("shi").toString();
                    dz = zxList.get(0).get("dz").toString();
                    for (Map<String, Object> stringObjectMap : zxList) {
                        zl += Double.valueOf(stringObjectMap.get("zl").toString());
                        sl += Double.valueOf(stringObjectMap.get("sl").toString());
                    }
                }else {
                    if (jpxList.size() > 0) {
                        lxr = jpxList.get(0).get("lxr").toString();
                        lxrdh = jpxList.get(0).get("lxrdh").toString();
                        sheng = jpxList.get(0).get("sheng").toString();
                        shi = jpxList.get(0).get("shi").toString();
                        dz = jpxList.get(0).get("dz").toString();
                        for (Map<String, Object> stringObjectMap : jpxList) {
                            zl += Double.valueOf(stringObjectMap.get("zl").toString());
                            sl += Double.valueOf(stringObjectMap.get("sl").toString());
                        }
                    } else {
                        throw new ServiceException("扫码失败，请检查箱编号");
                    }
                }
                json.put("partnerId",new String(PropertyUtil.getProperty("ckfh.partnerId").getBytes("ISO-8859-1"),"GBK"));
                json.put("net", new String(PropertyUtil.getProperty("ckfh.net").getBytes("ISO-8859-1"),"GBK"));
                json.put("partnerKey", new String(PropertyUtil.getProperty("ckfh.partnerKey").getBytes("ISO-8859-1"),"GBK"));
                json.put("kuaidicom", new String(PropertyUtil.getProperty("ckfh.kuaidicom").getBytes("ISO-8859-1"),"GBK"));
                json.put("kuaidinum", "");
                json.put("orderId", "");
                JSONObject recMan = new JSONObject();
                recMan.put("name", new String(PropertyUtil.getProperty("ckfh.recMan.name").getBytes("ISO-8859-1"),"GBK"));
                recMan.put("mobile", new String(PropertyUtil.getProperty("ckfh.recMan.mobile").getBytes("ISO-8859-1"),"GBK"));
                recMan.put("province", new String(PropertyUtil.getProperty("ckfh.recMan.province").getBytes("ISO-8859-1"),"GBK"));
                recMan.put("city", new String(PropertyUtil.getProperty("ckfh.recMan.city").getBytes("ISO-8859-1"),"GBK"));
                recMan.put("district", new String(PropertyUtil.getProperty("ckfh.recMan.district").getBytes("ISO-8859-1"),"GBK"));
                recMan.put("addr", new String(PropertyUtil.getProperty("ckfh.recMan.addr").getBytes("ISO-8859-1"),"GBK"));
                recMan.put("printAddr", new String(PropertyUtil.getProperty("ckfh.recMan.printAddr").getBytes("ISO-8859-1"),"GBK"));
                recMan.put("company", new String(PropertyUtil.getProperty("ckfh.recMan.company").getBytes("ISO-8859-1"),"GBK"));
                json.put("recMan", recMan);
                JSONObject sendMan = new JSONObject();
                sendMan.put("name", lxr);
                sendMan.put("mobile", lxrdh);
                sendMan.put("province", sheng);
                sendMan.put("city", shi);
                sendMan.put("district", "");
                sendMan.put("addr", "");
                sendMan.put("printAddr", dz);
                sendMan.put("company", "");
                json.put("sendMan", sendMan);
                json.put("cargo", "");
                json.put("count", sl);
                json.put("weight", map.get("width").toString());
                json.put("volumn", zl);
                json.put("payType", "");
                json.put("expType", PropertyUtil.getProperty("ckfh.expType"));
                json.put("remark", "");
                json.put("valinsPay", new Double(0));
                json.put("collection", new Double(0));
                json.put("needChild",new String(PropertyUtil.getProperty("ckfh.needChild").getBytes("ISO-8859-1"),"GBK"));
                json.put("needBack", new String(PropertyUtil.getProperty("ckfh.needBack").getBytes("ISO-8859-1"),"GBK"));
                json.put("needTemplate", new String(PropertyUtil.getProperty("ckfh.needTemplate").getBytes("ISO-8859-1"),"GBK"));

                Long t = System.currentTimeMillis();
                String key = new String(PropertyUtil.getProperty("ckfh.key").getBytes("ISO-8859-1"),"GBK");
                String secret = new String(PropertyUtil.getProperty("ckfh.secret").getBytes("ISO-8859-1"),"GBK");

                Map<String, Object> params = new HashMap<String, Object>();
                System.out.println("原文：" + json.toString() + t + key + secret);
                String sign = MD5.encode(json.toString() + t + key + secret);
                System.out.println("sign:" + sign);
                params.put("method", "getElecOrder");
                params.put("param", json.toString());
                params.put("sign", sign);
                params.put("t", t.toString());
                params.put("key", key);
                System.out.println(params.toString());
                json = JSONObject.fromObject(HttpUtil.doPost("http://api.kuaidi100.com/eorderapi.do", params).toString());
                json.toString();
                if(!(json.get("status").toString().equals("200"))){
                        JSONArray jsonArray = JSONArray.fromObject(json.get("data").toString());
                        JSONObject jsonObject = JSONObject.fromObject(jsonArray.get(0));
                        Map<String,Object> messageMap = new HashMap<>();
                        //发运公司
                        messageMap.put("ysgs",new String(PropertyUtil.getProperty("fydd.dx.kdgs").getBytes("ISO-8859-1"),"UTF-8"));
                        //快递单号
                        messageMap.put("ysdh",jsonObject.get("kuaidinum").toString());
                        messageMap.put("lxrxm",lxr);
                        messageMap.put("lxrdh",lxrdh);
                        //判断是否集拼箱
                        if(xbh.substring(0,3).equals("JPX")){
                            //如果是集拼箱查找所有装箱信息
                            WmsSetBox wmsSetBox = wmsSetBoxMapper.baseSelectByPrimaryXbh(xbh);
                            messageMap.put("jpxid",wmsSetBox.getId());
                            //写入快递信息
                            wmsSetBoxMapper.updateBoxMessageByJpxid(messageMap);
                        } else {
                            //如果是装箱则查询装箱
                            messageMap.put("xbh",xbh);
                            wmsSetBoxMapper.updateBoxMessageByZxid(messageMap);
                        }
                    throw new ServiceException(json.get("message").toString());
                }else{
                    json = JSONObject.fromObject(JSONArray.fromObject(json.get("data").toString()).get(0));
                    message = json.get("templateurl").toString();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("打印电子面单失败");
        }
        return message;
    }

    /**
     * 分页查询
     * @param entity 实体
     * @return Page<WmsReview>
     */
    @BaseServiceDescribe(moduleName = "出库复核",btnName = "列表页面查询")
    public Page<Map<String,Object>> baseSelectPage(WmsReview entity ){
        PageHelper.startPage(entity.getPage(),entity.getRows());
        return (Page<Map<String,Object>>)dao.baseSelectPage( entity );
    }

    /**
     * 查询（根据主键ID查询）
     * @param id 主键ID
     * @return WmsReview
     */
    public WmsReview baseSelectByPrimaryKey( String id ){
        return dao.baseSelectByPrimaryKey( id );
    }

    /**
     * 查询（根据ID 批量查询）
     * @param idList 主键ID列表
     * @return list
     */
    public Integer baseSelectBathPrimaryKeys( List<WmsReview> idList ){
        return dao.baseSelectBathPrimaryKeys( idList );
    }

    /**
     *修改 （匹配有值的字段）
     * @param list
     * @return int
     */
    @BaseServiceDescribe(moduleName = "出库复核",btnName = "修改出库复核")
    public void baseUpdateByPrimaryKeySelective( List<WmsReview> list,HttpSession session) throws SucessException,ServiceException{
        UserInfo userinfo= (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (WmsReview entity : list) {
            entity.setClr(userinfo.getUser().getName());
            entity.setClsj(formatter.format(new Date()));
            List<String> ids = new ArrayList<String>();
            ids.add(entity.getId());
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("fhzt",entity.getFhzt().toString());
            map.put("list",ids);
            dao.updatePickingFhzt(map);
            dao.baseUpdateByPrimaryKeySelective( entity );
        }
        throw new SucessException("修改出库复核成功");
    }


    /**
     *修改（根据主键ID修改）
     * @param entity 主键ID列表
     * @return int
     */
    public Integer baseUpdateByPrimaryKey( WmsReview entity){
        return dao.baseUpdateByPrimaryKey( entity);
    }

}
